Module# 15: Java and Utilities                                                                 Lecture#60: Java Cursors

 

 

//   Example 60.1 : Demonstration of enumeration

 

// Java program to demonstrate Enumeration

 

import java.util.Enumeration;

import java.util.Vector;

 

public class EnumerationTest  {

        public static void main(String[] args)      {

            // Create a vector and print its contents

            Vector v = new Vector();

             for (int i = 0; i < 10; i++)

                          v.addElement(i);

            System.out.println(v);

 

 

        /*Declare an enumerator to the collection v at the beginning e points to

      index just before the first element in v   */

 

      Enumeration e = v.elements();

 

      while (e.hasMoreElements()) {    // Enumerate each element one-by-one

            int i = (Integer)e.nextElement();      //Moving cursor to next element

                        System.out.print(i + " ");    // Print the current element

      }

      }

}

 

// Example 60.2 : Iterator object with ArrayList class

 

import java.util.*;

public class IteratorDemo {

      public static void main(String[] args)      {

      ArrayList<Integer> al = new ArrayList<Integer>();

       for (int i = 0; i < 10; i++)

                    al.add(i);

      System.out.println(al);

 

      Iterator itr = al.iterator();

           // The cursor at the beginning of the first element

      while (itr.hasNext()) {  // Iterate over each element in al

                     int i = itr.next();  // Read the current element

                     System.out.print(i + " ");

                     if (i % 2 != 0)

                      itr.remove();   // Removing odd elements

      }

             System.out.println(); 

             System.out.println(al);

       }

}

 

// Example 60.3 : Add or remove while using Iterator

 

import java.util.*;

 

public class ErrorWithIterator  {

        public static void main(String args[]){

      ArrayList<String> books = new ArrayList<String>();

      books.add("C");

      books.add("C++");

      books.add("Java”);

 

      for(String obj : books) {

              System.out.println(obj);

              books.add("C#");         // We are adding element while iterating list

            }

 

      Iterator itr = books.iterator();

      while (itr.hasNext()) { 

                   String b = itr.next();

                  System.out.print(b + " ");

                  books.add("Python");    // You cannot do it!

                  books.remove(“C”),      // You cannot do it!!

      }

       }

}

 

// Example 60.4 : ListIterator with ArrayList collection

 

import java.util.*;

 

class ListIteratorDemo {

    public static void main(String args[]) {

      // Create an array list.

      ArrayList<String> al = new ArrayList<String>();

      // Add elements to the array list.

      al.add("C");

      al.add("A");

      al.add("E");

      al.add("B");

      al.add("D");

      al.add("F");

   

      // Use iterator to display contents of al.

      System.out.print("Original contents of al: ");

       Iterator<String> itr = al.iterator();

      while(itr.hasNext()) {

            String element = itr.next();

            System.out.print(element + " ");

      }

      System.out.println();

 

      // Modify objects being iterated.

      ListIterator<String> litr = al.listIterator();

      while(litr.hasNext()) {

            String element = litr.next();

            litr.set(element + "+");

       }

      System.out.print("Modified contents of al: ");

   

      // Now, display the list backwards.

      System.out.print("Modified list backwards: ");

      while(litr.hasPrevious()) {

            String element = litr.previous();

            System.out.print(element + " ");

      }

       System.out.println();

       }

}

 

// Example 60.5 :  Cycle through a collection using for-each

 

import java.util.*;

class ForEachLoopDemo {

     public static void main(String args[]) {

      // Create an array list for integers.

      ArrayList<Integer> vals = new ArrayList<Integer>();

      // Add values to the array list.

      vals.add(1);

      vals.add(2);

      vals.add(3);

      vals.add(4);

      vals.add(5);

   

// Use for loop to display the values.

      System.out.print("Contents of vals: ");

       for(int v : vals)

             System.out.print(v + " ");

      System.out.println();

      // Now, sum the values by using a for loop.

      int sum = 0;

      for(int v : vals)

            sum += v;

      System.out.println("Sum of values: " + sum);

     }

}

 

// Example 60.6 :  Iterators references of different types to the same collection

 

import java.util.Enumeration;

import java.util.Iterator;

import java.util.ListIterator;

import java.util.Vector;

 

public class JavaCurorsTest {

     public static void main(String[] args) {

     Vector v = new Vector();

 

      // Create three iterators

      Enumeration e = v.elements();

      Iterator  itr = v.iterator();

      ListIterator ltr = v.listIterator();

 

      // Code to use the iterators

      }

}

 

// Example 60.7 :  Iterators references of different types to the same collection

 

public class Employee {

      private int empid;

      private String ename;

      private String designation;

      private double salary;

 

      public Employee(int empid,String ename,String designation,double salary){

      this.empid = empid;

      this.ename = ename;

      this.designation = designation;

      this.salary = salary;

     }

 

     public int getEmpid() {

      return empid;

     }

 

        public String getEname() {

      return ename;

        }

 

        public String getDesignation() {

      return designation;

        }

 

        public double getSalary() {

           return salary;

        } 

 

        //The fllowing shows how to print an element of custom type using toString()

        @Override

         public String toString(){

      return empid + "\t" + ename + "\t" + designation + "\t" + salary; 

      }

}

 

import java.util.*;

 

public class Employees implements Iterable{

     private List<Employee> emps = null;

     public Employees(){

      emps = new ArrayList<&glt;();

      emps.add(new Employee(101,"Ram","Professor", 250000L));

      emps.add(new Employee(102,"Rahim","Engineer", 300000L));

      emps.add(new Employee(1003,"Jonny","Doctor", 350000L));

      }

 

     @Override

      public Iterator<Employee> iterator() {

      return emps.iterator();

      }

}

 

public class EmployeesTester {

      public static void main(String[] args) {

      Employees emps = new Employees();

      for(Employee emp : emps){

                  System.out.println(emp);

      }

       }

}

 

 

 

// Example 60.8 : Spliterator illustration

 

import java.util.*;

 

class SpliteratorDemo {

     public static void main(String args[]) {

      // Create an array list for doubles.

      ArrayList<Double> vals = new ArrayList<>();

   

      // Add values to the array list.

      vals.add(1.0);

      vals.add(2.0);

      vals.add(3.0);

      vals.add(4.0);

      vals.add(5.0);

 

     // Use tryAdvance() to display contents of vals.

      System.out.println("Contents of vals: ");

      Spliterator<Double> spltitr = vals.spliterator();

      while(spltitr.tryAdvance((n)-> System.out.println(n)));

                  System.out.println();

   

      // Create new list that contains square roots.

      spltitr = vals.spliterator();

      ArrayList<Double> sqrs = new ArrayList<>();

      while(spltitr.tryAdvance((n) -> sqrs.add(Math.sqrt(n))));

            // Use forEachRemaining() to display contents of sqrs.

            System.out.print("Contents of sqrs:\n");

   

      spltitr = sqrs.spliterator();

      spltitr.forEachRemaining((n) -> System.out.println(n));

      System.out.println();

      }

}

 

// Example 60.9 : Utility of other methods of Spliterator

 

import java.util.*;

     

public class SpliteratorDemo  {

public static void main(String[] args)  {

            // Create an array list for doubles.

            ArrayList<Integer> al = new ArrayList<>();

         

            // Add values to the array list.

            al.add(1);

            al.add(2);

            al.add(-3);

            al.add(-4);

            al.add(5);

         

            // Obtain a Stream to the array list.

            Stream<Integer> str = al.stream();

         

            // getting Spliterator object on al

            Spliterator<Integer> splitr1 = str.spliterator();

     

            // estimateSize method

            System.out.println("estimate size : " + splitr1.estimateSize());

 

            // getExactSizeIfKnown method

            System.out.println("exact size : " + splitr1.getExactSizeIfKnown());

            // hasCharacteristics and characteristics method

      System.out.println(splitr1.hasCharacteristics(splitr1.characteristics()));

            System.out.println("Content of arraylist :");

   

// forEachRemaining method    

            splitr1.forEachRemaining((n) -> System.out.println(n));

            // Obtaining another  Stream to the array list.

            Stream<Integer> str1 = al.stream();

            splitr1 = str1.spliterator();

            // trySplit() method

            Spliterator<Integer> splitr2 = splitr1.trySplit();

            // If splitr1 could be split, use splitr2 first.

            if(splitr2 != null) {

                     System.out.println("Output from splitr2: ");

                     splitr2.forEachRemaining((n) -> System.out.println(n));

            }

             // Now, use the splitr

            System.out.println("\nOutput from splitr1: ");

            splitr1.forEachRemaining((n) -> System.out.println(n));

          }

}

 

// Example 60.10 : Simple Spliterator using tryAdvance() method

 

import java.util.ArrayList;

import java.util.Spliterator;

public class SpliteratorDemo{

        public static void main(String[] args){

            // Create an array list for doubles.

            ArrayList<Integer> al1 = new ArrayList<>();

            // Add values to the array list.

            al1.add(1);

            al1.add(2);

            al1.add(-3);

            al1.add(-4);

            al1.add(5);

 

            // Use tryAdvance() to display(action) contents of arraylist.

            System.out.print("Contents of arraylist:\n");

 

            // getting Spliterator object on al1

            Spliterator<Integer> splitr = al1.spliterator();

            // Use tryAdvance() to display(action) contents of arraylist.

            // Notice how lambda expression is used to implement accept method

            // of Consumer interface

 

while(splitr.tryAdvance((n) -> System.out.println(n)));  

                 // Use tryAdvance() for getting absolute values(action) of contents of arraylist. 

                 // Create new list that contains absolute values.

                  ArrayList<Integer> al2 = new ArrayList<>();

                  splitr = al1.spliterator();

                  // Here our action is to get absolute values

                  // Notice how lambda expression is used to implement accept method

                  // of Consumer interface

            while(splitr.tryAdvance((n) -> al2.add(Math.abs(n)))); 

                    System.out.print("Absolute values of contents of arraylist:\n");   

       

// getting Spliterator object on al2

            splitr = al2.spliterator();

            while(splitr.tryAdvance((n) -> System.out.println(n))); 

      }

}